package com.dtt.company.employee.servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

import com.dtt.company.employee.model.EmployeeModel;
import com.dtt.company.employee.service.EmployeeService;
import com.dtt.company.util.FmtRequest;
import com.dtt.company.util.UploadUtil;

@WebServlet("/EmployeeUpload")
public class EmployeeUploadServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private EmployeeService service=new EmployeeService();
	//上传使用dopost
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("EmployeeUpload-----------");
		Map<String, Object> map =null;
		try {
			map = UploadUtil.upload(req);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		String code=map.get("code").toString();
		EmployeeModel model = new EmployeeModel();
		model.setCode(code);
		EmployeeModel mdb = service.selectModel(model);//查找该用户信息
		String image=mdb.getHead();//找到该用户的头像
		if(image!=null&&!image.trim().isEmpty()) {//如果该用户已有头像，再次上传时，要把原来的头像在服务器端删除
			UploadUtil.delFile(mdb.getHead());
		}
		
		List<String> list=(List<String>) map.get("list");
		image=list.get(0);
		model.setHead(list.get(0));//上传的文件名
		
		String res=service.update(model);
		
		Map<String,String> result=new HashMap<>();
		result.put("code",res);
		result.put("image",image);
		
		FmtRequest.out(resp, new JSONObject(result).toString());
	}

}
	
